import { getCompanyID, getLoadMapList, getPosIDs, getTenantID, getUserDepID, getUserID, onCloseModalCommon } from '@/utils';
import { Button, Col, Form, Input, message, Row, Select, Spin } from 'antd';
import { Ref, useRef } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import React from 'react';
import { cancelModalRequest } from './services';
import { CloseCircleOutlined, CheckCircleOutlined } from '@ant-design/icons';

export const CancelModal = React.forwardRef<CancelModalAPI.ICancelModalRefs, CancelModalAPI.ICancelModals>(
  (
    {
      onClose,
      checkRows,
      reloadManage,
      modalTitle,
      cancelTypeDic,
      cancelRequestUrl,
      cancelRequestBody = {},
      modalWidth = 0.25,
      cancelRequestType = 'PUT',
      cancelFormType = 'cancelType',
      cancelFormTypeName = '作废类型',
      cancelFormTypeRequired = true,
      cancelFormReason = 'cancelReason',
      cancelFormReasonName = '作废原因',
      cancelFormReasonRequired = false,
    },
    ref,
  ) => {
    /**
     * modal ref
     */
    const cancelModalRef: Ref<IOneModalRef> = useRef(null);

    /**
     * 关闭弹窗
     */
    const onCloseModal = () => {
      if (cancelModalRef) {
        if (cancelModalRef.current) {
          if (cancelModalRef.current.onModalCancel) {
            cancelModalRef.current.onModalCancel();
          }
        }
      }
    };

    /**
     * 表单 form
     */
    const [cancelForm] = Form.useForm();

    /**  获取数据字典 */
    const { loadMapInfo, mapLoading } = getLoadMapList([`${getTenantID()}${cancelTypeDic}`]);

    /**
     * 作废接口回调
     */
    const cancelModalCall = (res: Record<string, any>) => {
      if (res && res?.msgFlag) {
        message.success(res?.msg);
        reloadManage();
        onCloseModal();
      } else {
        message.error(res?.msg);
      }
    };

    /**
     * 引入作废接口
     */
    const { cancelModalLoading, cancelModalRun } = cancelModalRequest(cancelModalCall, cancelRequestType, cancelRequestUrl);

    /**
     * 保存
     */
    const saveCancelOnOk = () => {
      cancelForm?.validateFields()?.then((values: any) => {
        let payload: Record<string, any> = {
          ...values,
          id: checkRows?.id,
          versionNum: checkRows?.versionNum,
          ...cancelRequestBody,
          cancelerID: getUserID(),
          cancelPositionID: getPosIDs(),
          cancelDepartmentID: getUserDepID(),
          cancelCompanyID: getCompanyID(),
        };
        cancelModalRun(payload);
      });
    };

    return (
      <>
        <OneModal
          open={true}
          ref={cancelModalRef}
          title={modalTitle}
          width={document.body.clientWidth * modalWidth}
          onCancel={onClose}
          bodyStyle={{
            padding: '5px 0px',
          }}
          centered
          footer={[
            <Button
              key="back"
              loading={cancelModalLoading || mapLoading}
              onClick={() => {
                onCloseModalCommon(cancelModalRef);
              }}
              // icon={<CloseCircleOutlined />}
            >
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              loading={cancelModalLoading || mapLoading}
              onClick={saveCancelOnOk}
              // icon={<CheckCircleOutlined />}
            >
              确定
            </Button>,
          ]}
          confirmLoading={cancelModalLoading || mapLoading}
        >
          <Spin spinning={cancelModalLoading || mapLoading}>
            <div className={pageStyles['fromView-styles']}>
              <Form form={cancelForm}>
                <Row>
                  <Col span={24}>
                    <Form.Item
                      label={cancelFormTypeName}
                      name={cancelFormType}
                      rules={[
                        {
                          required: cancelFormTypeRequired,
                          message: `请选择${cancelFormTypeName}`,
                        },
                      ]}
                    >
                      <Select placeholder={`请选择${cancelFormTypeName}`} allowClear loading={mapLoading}>
                        {loadMapInfo?.[`${getTenantID()}${cancelTypeDic}`]?.map((item: any) => {
                          return (
                            <Select.Option key={item?.id} value={item?.id}>
                              {item?.name}
                            </Select.Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                  </Col>

                  <Col span={24}>
                    <Form.Item
                      label={cancelFormReasonName}
                      name={cancelFormReason}
                      rules={[
                        {
                          required: cancelFormReasonRequired,
                          message: `请输入${cancelFormReasonName}`,
                        },
                      ]}
                    >
                      <Input.TextArea placeholder={`请输入${cancelFormReasonName}`} showCount maxLength={200} autoSize={{ minRows: 2, maxRows: 4 }} />
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </div>
          </Spin>
        </OneModal>
      </>
    );
  },
);
